package com.eam.eventhandler;

import com.eam.data.EamFacilitiesMaintain;
import com.eam.data.EamMaintainPlanItems;
import com.eam.data.EamMaintainPlanFacs;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;
import java.util.List;

public class MaintainItemEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EamMaintainPlanFacs.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}
	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}
		String results = "";
		
		//获取item
		EamMaintainPlanFacs item = (EamMaintainPlanFacs) event.getTargetInstance();
		
		String status = item.getEamMaintainPlan().getStatus();   //计划状态
		String type = item.getEamMaintainPlan().getDistinguish();   //计划类型（区分是保养计划还说维修清单）
		String plan_id = item.getEamMaintainPlan().getId();	//计划ID
		String itemstatus = item.getStatus();  //设备状态
		String plancycle = item.getEamMaintainPlan().getPlanType();    //保养计划层的保养周期
		
		if(status.equals("OK")){
			results = "已完成";
		}else if(status.equals("UNAPPROVED")){
			results = "待审核";
			
		}else if(status.equals("SERVICE")){
			results = "维保中";
		}
		
		if(type.equals("MAINTAIN")){
			//等于保养计划时才进入该判断
			if(status.equals("OK") || status.equals("UNAPPROVED")||status.equals("SERVICE")){
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
		        throw new OBException(Utility.messageBD(conn, "该计划状态为"+results+"，不可修改！", language));
			}else{
			
				//获取item
				String f_id = item.getEamFacilities().getId();
					
				if(itemstatus.equals("OK")){
					String language = OBContext.getOBContext().getLanguage().getLanguage();
			        ConnectionProvider conn = new DalConnectionProvider(false);
			        throw new OBException(Utility.messageBD(conn, "该设备已完成，不可修改！", language));
				}else{
					
					
					
					
					
					String sql = "select t from " + EamMaintainPlanFacs.ENTITY_NAME + "  t where  t.eamFacilities.id = :f_id and t.eamMaintainPlan.id = :plan_id";
					Query query = OBDal.getInstance().getSession().createQuery(sql);
					query.setString("f_id", f_id);
					query.setString("plan_id", plan_id);
					

					if(query.list().size() > 1){
						String language = OBContext.getOBContext().getLanguage().getLanguage();
				        ConnectionProvider conn = new DalConnectionProvider(false);
				        throw new OBException(Utility.messageBD(conn, item.getEamFacilities().getName()+"已经在该计划中，请仔细检查！！", language));
					}else{
						
						String eql = "delete from " + EamMaintainPlanItems.ENTITY_NAME + " where Eam_Maintain_Plan_Facs_id = ? ";
												
						OBDal.getInstance().getSession().createSQLQuery(eql).setString(0, item.getId()).executeUpdate();

						//获取设备维修、保养项目配置里设备配置的保养项目并保存下来
						String aql = "select main from " + EamFacilitiesMaintain.ENTITY_NAME + " main where main.eamFacilities.id = :f_id and main.planType = :plancycle ";
						Query querys = OBDal.getInstance().getSession().createQuery(aql);
						querys.setString("f_id", f_id);
						querys.setString("plancycle", plancycle);
						List<EamFacilitiesMaintain> list = querys.list();
						
						for(EamFacilitiesMaintain mains : list){
							EamMaintainPlanItems details = new EamMaintainPlanItems(); //计划下设备下的项目层(第三层)
							details.setEamMaintainPlanFacs(item);
							details.setPlanUser(mains.getPlanUser());
							details.setEamMaintainItem(mains.getEamMaintainItem());
							details.setGroupUser(mains.getGroupUser());
							OBDal.getInstance().save(details);
							
							
						}
					}
				}
		
			}
		}
		
		
	}
	
	
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		
		EamMaintainPlanFacs item = (EamMaintainPlanFacs) event.getTargetInstance();   //计划下设备层（第二层）
		
		
		String status = item.getEamMaintainPlan().getStatus();  //保养计划的状态
		String plan_id = item.getEamMaintainPlan().getId();    //保养计划层的ID
		String plancycle = item.getEamMaintainPlan().getPlanType();    //保养计划层的保养周期
		 
		
		
		if(status.equals("OK") ||status.equals("UNAPPROVED")){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
	        ConnectionProvider conn = new DalConnectionProvider(false);
	        throw new OBException(Utility.messageBD(conn, "该计划已维保完，不可新增设备！", language));
		}else{
		
			//获取item中设备的ID
			String f_id = item.getEamFacilities().getId();
				
			String sql = "select t from " + EamMaintainPlanFacs.ENTITY_NAME + "  t where  t.eamFacilities.id = :f_id and t.eamMaintainPlan.id = :plan_id";
			Query query = OBDal.getInstance().getSession().createQuery(sql);
			query.setString("f_id", f_id);
			query.setString("plan_id", plan_id);
			
			
			//获取设备维修、保养项目配置里设备配置的保养项目并保存下来
			String aql = "select main from " + EamFacilitiesMaintain.ENTITY_NAME + " main where main.eamFacilities.id = :f_id and main.plantype = :plancycle ";
			Query querys = OBDal.getInstance().getSession().createQuery(aql);
			querys.setString("f_id", f_id);
			querys.setString("plancycle", plancycle);
			
			List<EamFacilitiesMaintain> list = querys.list();
			
			for(EamFacilitiesMaintain mains : list){
				EamMaintainPlanItems details = new EamMaintainPlanItems(); //计划下设备下的项目层(第三层)
				details.setEamMaintainPlanFacs(item);
				details.setPlanUser(mains.getPlanUser());
				details.setEamMaintainItem(mains.getEamMaintainItem());
				details.setGroupUser(mains.getGroupUser());
				OBDal.getInstance().save(details);
				
				
			}
			
			if(query.list().size() > 0){
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
		        throw new OBException(Utility.messageBD(conn, item.getEamFacilities().getName()+"已经在该计划中，请仔细检查！！", language));
			}
		}
		
	}
	
	public void onDelete(@Observes
	EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}
	
}
